package com.rupeng.web.interceptor;

import com.rupeng.pojo.User;
import com.rupeng.service.UserService;
import com.rupeng.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AutoLoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User)request.getSession().getAttribute("user");
        if (user!=null){
            return true;
        }
        Cookie loginNameCookie = WebUtils.getCookie(request, "loginName");
        Cookie loginPasswordCookie = WebUtils.getCookie(request, "loginPassword");
        if (loginNameCookie==null || loginPasswordCookie==null) {
            return true;
        }
        String loginName = loginNameCookie.getValue();
        String loginPassword = loginPasswordCookie.getValue();
        user = new User();
        if (CommonUtils.isEmail(loginName)){
            user.setEmail(loginName);
        } else {
            user.setPhone(loginName);
        }
        user = userService.selectOne(user);
        if (user.getPassword().equals(loginPassword)){
            request.getSession().setAttribute("user",user);
        }
        return true;
    }
}
